<template>
  <div class="page-container">
    <div class="page-header">
      <h2>班级管理</h2>
    </div>
    
    <div class="operation-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true">新增班级</el-button>
        </el-col>
        <el-col :span="12">
          <el-input v-model="searchText" placeholder="请输入班级名称搜索" clearable>
            <template #append>
              <el-button :icon="Search" @click="searchClass"></el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>
    
    <div class="table-container">
      <el-table :data="filteredClassList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="班级名称"></el-table-column>
        <el-table-column prop="grade" label="年级"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column prop="studentCount" label="学生数量"></el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewStudents(scope.row)">查看学生</el-button>
            <el-button type="warning" size="small" @click="editClass(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteClass(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 新增/编辑班级弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑班级' : '新增班级'" width="500px">
      <el-form :model="classForm" :rules="classRules" ref="classFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="classForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="classForm.major"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitClassForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看学生弹窗 -->
    <el-dialog v-model="studentDialogVisible" title="学生列表" width="800px">
      <div class="student-import-container" style="margin-bottom: 15px;">
        <el-upload
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx, .csv">
          <el-button type="primary">从Excel导入</el-button>
        </el-upload>
        <el-button type="success" @click="importExcel" :disabled="!selectedFile" style="margin-left: 10px;">
          确认导入
        </el-button>
        <el-button type="primary" @click="addStudentDialogVisible = true" style="margin-left: 10px;">
          手动添加
        </el-button>
      </div>
      
      <el-table :data="currentClassStudents" border style="width: 100%">
        <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="grade" label="年级"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteStudent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    
    <!-- 添加学生弹窗 -->
    <el-dialog v-model="addStudentDialogVisible" title="添加学生" width="500px">
      <el-form :model="studentForm" :rules="studentRules" ref="studentFormRef" label-width="100px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="studentForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addStudentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStudentForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import { classApi } from '../utils/api'

// 工厂模式 - 文件解析器工厂
class FileParserFactory {
  static createParser(fileType) {
    switch (fileType) {
      case 'xlsx':
      case 'xls':
        return new ExcelParser()
      case 'csv':
        return new CsvParser()
      default:
        throw new Error('不支持的文件类型')
    }
  }
}

// Excel解析器
class ExcelParser {
  parse(file, callback) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const data = e.target.result
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      callback(this.formatData(jsonData))
    }
    reader.readAsArrayBuffer(file)
  }
  
  formatData(jsonData) {
    return jsonData.map(item => ({
      studentId: item['学号'] || '',
      name: item['姓名'] || '',
      grade: item['年级'] || '',
      major: item['专业'] || ''
    }))
  }
}

// CSV解析器
class CsvParser {
  parse(file, callback) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const csvData = e.target.result
      // CSV解析逻辑
      callback(this.formatData(csvData))
    }
    reader.readAsText(file)
  }
  
  formatData() {
    // CSV数据格式化逻辑
    return []
  }
}

export default {
  name: 'ClassManagement',
  setup() {
    // 数据
    const classList = ref([])
    
    const students = ref({})
    
    // 加载班级列表
    const loadClasses = async () => {
      try {
        const data = await classApi.getClasses()
        classList.value = data || []
      } catch (error) {
        ElMessage.error('获取班级列表失败')
        console.error(error)
      }
    }
    
    // 加载学生列表
    const loadStudents = async (classId) => {
      try {
        const data = await classApi.getStudents(classId)
        students.value[classId] = data || []
        return data
      } catch (error) {
        ElMessage.error('获取学生列表失败')
        console.error(error)
        return []
      }
    }
    
    // 在组件挂载时加载班级列表
    onMounted(() => {
      loadClasses()
    })
    
    // 搜索相关
    const searchText = ref('')
    const filteredClassList = computed(() => {
      if (!searchText.value) return classList.value
      return classList.value.filter(cls => 
        cls.name.includes(searchText.value) || 
        cls.grade.includes(searchText.value) ||
        cls.major.includes(searchText.value)
      )
    })
    
    const searchClass = () => {
      // 已经通过计算属性实现了搜索功能
    }
    
    // 班级表单相关
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const classForm = reactive({
      id: '',
      name: '',
      grade: '',
      major: ''
    })
    
    const classRules = {
      name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
      grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
      major: [{ required: true, message: '请输入专业', trigger: 'blur' }]
    }
    
    const classFormRef = ref(null)
    
    const resetClassForm = () => {
      classForm.id = ''
      classForm.name = ''
      classForm.grade = ''
      classForm.major = ''
      
      if (classFormRef.value) {
        classFormRef.value.resetFields()
      }
    }
    
    const editClass = (row) => {
      isEdit.value = true
      Object.assign(classForm, row)
      dialogVisible.value = true
    }
    
    const submitClassForm = async () => {
      if (!classFormRef.value) return
      
      await classFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (isEdit.value) {
              // 编辑模式
              await classApi.updateClass(classForm.id, classForm)
              ElMessage.success('班级编辑成功')
            } else {
              // 新增模式
              await classApi.createClass(classForm)
              ElMessage.success('班级添加成功')
            }
            
            // 重新加载班级列表
            await loadClasses()
            dialogVisible.value = false
            resetClassForm()
            isEdit.value = false
          } catch (error) {
            ElMessage.error(isEdit.value ? '班级编辑失败' : '班级添加失败')
            console.error(error)
          }
        }
      })
    }
    
    const deleteClass = (row) => {
      ElMessageBox.confirm('确定要删除该班级吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await classApi.deleteClass(row.id)
          ElMessage.success('删除成功')
          // 重新加载班级列表
          await loadClasses()
        } catch (error) {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }).catch(() => {})
    }
    
    // 学生管理相关
    const studentDialogVisible = ref(false)
    const currentClassId = ref(null)
    const currentClassStudents = ref([])
    
    const viewStudents = async (row) => {
      currentClassId.value = row.id
      try {
        const data = await loadStudents(row.id)
        currentClassStudents.value = data
        studentDialogVisible.value = true
      } catch (error) {
        ElMessage.error('获取学生列表失败')
        console.error(error)
      }
    }
    
    // 导入Excel相关
    const fileList = ref([])
    const selectedFile = ref(null)
    
    const handleFileChange = (file) => {
      fileList.value = [file]
      selectedFile.value = file.raw
    }
    
    const importExcel = () => {
      if (!selectedFile.value) {
        ElMessage.warning('请先选择文件')
        return
      }
      
      try {
        const fileExt = selectedFile.value.name.split('.').pop().toLowerCase()
        if (fileExt !== 'xlsx' && fileExt !== 'csv') {
          ElMessage.error('仅支持xlsx或csv格式的文件')
          return
        }
        const parser = FileParserFactory.createParser(fileExt)
        
        parser.parse(selectedFile.value, async () => {
          try {
            // 使用API导入学生
            const formData = new FormData()
            formData.append('file', selectedFile.value)
            const result = await classApi.importStudents(currentClassId.value, selectedFile.value)
            
            ElMessage.success(`成功导入${result.length || 0}名学生`)
            
            // 重新加载学生列表
            const updatedStudents = await loadStudents(currentClassId.value)
            currentClassStudents.value = updatedStudents
            
            // 清空文件选择
            fileList.value = []
            selectedFile.value = null
          } catch (error) {
            ElMessage.error(`导入失败: ${error.message}`)
            console.error(error)
          }
        })
      } catch (error) {
        ElMessage.error(`导入失败: ${error.message}`)
        console.error(error)
      }
    }
    
    // 手动添加学生相关
    const addStudentDialogVisible = ref(false)
    const studentForm = reactive({
      studentId: '',
      name: '',
      grade: '',
      major: ''
    })
    
    const studentRules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ]
    }
    
    const studentFormRef = ref(null)
    
    const resetStudentForm = () => {
      studentForm.studentId = ''
      studentForm.name = ''
      studentForm.grade = ''
      studentForm.major = ''
      
      if (studentFormRef.value) {
        studentFormRef.value.resetFields()
      }
    }
    
    const submitStudentForm = async () => {
      if (!studentFormRef.value) return
      
      await studentFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 使用API添加学生
            await classApi.addStudent(currentClassId.value, studentForm)
            
            // 重新加载学生列表
            const updatedStudents = await loadStudents(currentClassId.value)
            currentClassStudents.value = updatedStudents
            
            // 更新班级列表（学生数量可能发生变化）
            await loadClasses()
            
            addStudentDialogVisible.value = false
            resetStudentForm()
            ElMessage.success('学生添加成功')
          } catch (error) {
            ElMessage.error('学生添加失败')
            console.error(error)
          }
        }
      })
    }
    
    const deleteStudent = (row) => {
      ElMessageBox.confirm('确定要删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 使用API删除学生
          await classApi.deleteStudent(currentClassId.value, row.id)
          
          // 重新加载学生列表
          const updatedStudents = await loadStudents(currentClassId.value)
          currentClassStudents.value = updatedStudents
          
          // 更新班级列表（学生数量可能发生变化）
          await loadClasses()
          
          ElMessage.success('删除成功')
        } catch (error) {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }).catch(() => {})
    }
    
    return {
      // 数据
      classList,
      filteredClassList,
      searchText,
      searchClass,
      Search,
      
      // 班级表单相关
      dialogVisible,
      isEdit,
      classForm,
      classRules,
      classFormRef,
      editClass,
      submitClassForm,
      deleteClass,
      
      // 学生管理相关
      studentDialogVisible,
      currentClassStudents,
      viewStudents,
      
      // 导入Excel相关
      fileList,
      selectedFile,
      handleFileChange,
      importExcel,
      
      // 手动添加学生相关
      addStudentDialogVisible,
      studentForm,
      studentRules,
      studentFormRef,
      submitStudentForm,
      deleteStudent
    }
  }
}
</script>

<style scoped>
.student-import-container {
  display: flex;
  align-items: center;
}
</style> 